package com.hfi.restful.web.aspect;

import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * 因为使用了@RestControllerAdvice controller中的try-catch模板代码就不需要写了
 * @author ChangLiang
 * @date 2019/9/5
 */
@Component
@Aspect
public class ControllerTryCatchAspect {

    private Logger logger = LoggerFactory.getLogger(getClass());

    public static final String REQUEST_OK = "200";

    /// @Around是可以改变controller返回值的
    /*@Around("execution(* com.hfi.restful.web.controller.UserController.*(..))")
    public Object handleControllerMethod(ProceedingJoinPoint pjp) throws Throwable {
        // 放行
        Object proceed = pjp.proceed();
        if (proceed != null) {
            Response response = (Response) proceed;
            if (StringUtils.equals(REQUEST_OK, response.getErrorcode())) {
                return response;
            } else {
                logger.error("errorcode:{}, path:{}", response.getErrorcode(), response.getValue());
                response = new Response();
                response.setErrorcode(ErrorCode.ERROR.value);
                response.setValue("自定义500异常");
                return response;
            }
        }
        return null;
    }

    @AfterReturning(returning = "returnVal", pointcut = "execution(* com.hfi.restful.web.controller.UserController.*(" +
            "..))")
    public Object handleReturning(JoinPoint pjp, Object returnVal) throws Throwable {
        if (returnVal != null) {
            Response proceed = (Response) returnVal;
            if (StringUtils.equals(REQUEST_OK, proceed.getErrorcode())) {
                return proceed;
            } else {
                logger.error("errorcode:{}, path:{}", proceed.getErrorcode(), proceed.getValue());
                Response response = new Response();
                response.setErrorcode(ErrorCode.ERROR.value);
                response.setValue(ErrorCode.ERROR.memo);
                return response;
            }
        }
        return null;
    }

    @AfterThrowing(throwing = "ex", pointcut = "execution(* com.hfi.restful.web.controller.UserController.*(..))")
    public void handleThrowing(Throwable ex) throws Throwable {
        logger.error(ex.getMessage());
    }*/
}
